package com.smart.manager.system.handler;


import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Administrator
 */
@Component
@RequiredArgsConstructor
public class TaskRegHandler implements DisposableBean {

    /**
     * 定理一个单例缓存
     */
    private final Map<Runnable, TaskCleanHandler> scheduledTasks = new ConcurrentHashMap<>(16);

    private final TaskScheduler taskScheduler;

    /**
     * 摧毁计划任务
     */
    @Override
    public void destroy() {
        for (TaskCleanHandler task : this.scheduledTasks.values()) {
            task.cancel();
        }
        this.scheduledTasks.clear();
    }


    /**
     * 添加一个定时任务
     * 其核心就是靠spring提供的 CronTask 类来实现
     *
     * @param task           任务对象
     * @param cronExpression 时间表达式
     */
    public void addTask(Runnable task, String cronExpression) {
        this.register(new CronTask(task, cronExpression));
    }

    /**
     * 注册程序
     */

    public void register(CronTask cronTask) {
        if (cronTask != null) {
            Runnable task = cronTask.getRunnable();
            if (this.scheduledTasks.containsKey(task)) {
                removeCronTask(task);
            }
            this.scheduledTasks.put(task, scheduleCronTask(cronTask));
        }
    }

    /**
     * 删除cron任务
     *
     * @param task 任务
     */
    public void removeCronTask(Runnable task) {
        TaskCleanHandler taskCleanHandler = this.scheduledTasks.remove(task);
        if (taskCleanHandler != null) {
            taskCleanHandler.cancel();
        }
    }

    /**
     * 安排cron任务
     *
     * @param cronTask cron任务
     * @return {@code TaskCleanHandler}
     */
    private TaskCleanHandler scheduleCronTask(CronTask cronTask) {
        TaskCleanHandler taskCleanHandler = new TaskCleanHandler();
        taskCleanHandler.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        return taskCleanHandler;
    }


}